package com.xingbg.projectimpl.config.customimpl;

import com.xingbg.projectimpl.config.EnableCustomWeb;
import com.xingbg.projectimpl.config.controller.LiskovRequestCondition;
import com.xingbg.projectimpl.config.controller.LiskovRequestMappingHandlerMapping;
import com.xingbg.projectimpl.config.controller.LiskovWebMvcConfigurationSupport;
import lombok.SneakyThrows;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public class LiskovWebDefinitionRegistar implements ImportBeanDefinitionRegistrar {

    @SneakyThrows
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(EnableCustomWeb.class.getName(), true);
        String[] basePackages =  (String[]) annotationAttributes.get("basePackages");
        if (basePackages==null || basePackages.length==0) {
            String basePackage = Class.forName(annotationMetadata.getClassName()).getPackage().getName();
            basePackages = new String[]{basePackage};
        }

        BeanDefinitionBuilder requestConditionBuilder = BeanDefinitionBuilder.genericBeanDefinition(LiskovRequestCondition.class);
        requestConditionBuilder.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        beanDefinitionRegistry.registerBeanDefinition(this.getBeanName("requestCnd",basePackages),requestConditionBuilder.getBeanDefinition());

        BeanDefinitionBuilder requestMappingBuilder = BeanDefinitionBuilder.rootBeanDefinition(LiskovRequestMappingHandlerMapping.class);
        requestMappingBuilder.addConstructorArgValue(basePackages);
        beanDefinitionRegistry.registerBeanDefinition(this.getBeanName("requestMappingHdl",basePackages),requestMappingBuilder.getBeanDefinition());

        BeanDefinitionBuilder mvcSupportBuilder = BeanDefinitionBuilder.rootBeanDefinition(LiskovWebMvcConfigurationSupport.class);
        mvcSupportBuilder.addConstructorArgValue(basePackages);
        beanDefinitionRegistry.registerBeanDefinition(this.getBeanName("webMvcCfgSpt",basePackages),mvcSupportBuilder.getBeanDefinition());

    }

    private String getBeanName(String name,String[] basePackages) {
        return name+String.join("-",basePackages);
    }
}
